// SQL Formatter 渲染器
window.SQLFormatterRenderer = class SQLFormatterRenderer {
    static getHTML() {
        return `
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-3xl font-bold text-gray-800">SQL 格式化工具</h2>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-500">
                        <span id="sql-status" class="font-medium">就绪</span>
                    </div>
                </div>
            </div>

            <!-- 格式化选项 -->
            <div class="bg-gray-50 border rounded-lg p-4 mb-6">
                <div class="grid md:grid-cols-4 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">缩进大小:</label>
                        <select id="indent-size" class="form-select text-sm border-gray-300 rounded-md w-full">
                            <option value="2">2 空格</option>
                            <option value="4" selected>4 空格</option>
                            <option value="8">8 空格</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">关键字大小写:</label>
                        <select id="keyword-case" class="form-select text-sm border-gray-300 rounded-md w-full">
                            <option value="upper" selected>大写</option>
                            <option value="lower">小写</option>
                            <option value="preserve">保持原样</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">逗号风格:</label>
                        <select id="comma-style" class="form-select text-sm border-gray-300 rounded-md w-full">
                            <option value="trailing" selected>尾随</option>
                            <option value="leading">前置</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">语句间隔:</label>
                        <select id="lines-between" class="form-select text-sm border-gray-300 rounded-md w-full">
                            <option value="0">无空行</option>
                            <option value="1" selected>1空行</option>
                            <option value="2">2空行</option>
                        </select>
                    </div>
                </div>
                
                <!-- 工具栏 -->
                <div class="flex flex-wrap items-center gap-3">
                    <button id="format-sql" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="align-left" class="w-4 h-4 mr-2"></i>
                        格式化
                    </button>
                    <button id="minify-sql" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="minimize-2" class="w-4 h-4 mr-2"></i>
                        压缩
                    </button>
                    <button id="validate-sql" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="check-circle" class="w-4 h-4 mr-2"></i>
                        验证
                    </button>
                    <button id="extract-tables" class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="database" class="w-4 h-4 mr-2"></i>
                        提取表名
                    </button>
                    <button id="copy-sql-result" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center" disabled>
                        <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                        复制结果
                    </button>
                    <button id="clear-sql" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                        清空
                    </button>
                    <button id="paste-sql" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="clipboard" class="w-4 h-4 mr-2"></i>
                        粘贴
                    </button>
                </div>
            </div>

            <!-- 内容区域 -->
            <div class="grid md:grid-cols-2 gap-6">
                <!-- 输入区域 -->
                <div>
                    <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                        <i data-feather="edit-3" class="w-5 h-5 mr-2"></i>
                        原始 SQL
                    </h3>
                    <textarea id="sql-input" class="w-full h-96 p-4 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm" placeholder="请输入SQL语句，例如：&#10;SELECT id, name, email FROM users WHERE created_at > '2023-01-01' AND status = 'active' ORDER BY name;"></textarea>
                    <div class="mt-2 text-sm text-gray-500 flex justify-between">
                        <span>字符数: <span id="sql-input-count">0</span></span>
                        <span>行数: <span id="sql-input-lines">0</span></span>
                    </div>
                </div>

                <!-- 输出区域 -->
                <div>
                    <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                        <i data-feather="code" class="w-5 h-5 mr-2"></i>
                        格式化结果
                    </h3>
                    <div id="sql-output" class="w-full h-96 p-4 bg-gray-50 border border-gray-300 rounded-lg font-mono text-sm overflow-auto whitespace-pre"></div>
                    
                    <!-- 结果统计 -->
                    <div id="sql-stats" class="mt-4 text-sm text-gray-600 hidden">
                        <div class="grid grid-cols-2 gap-4">
                            <div>原始长度: <span id="original-length" class="font-medium"></span></div>
                            <div>格式化长度: <span id="formatted-length" class="font-medium"></span></div>
                            <div>语句数量: <span id="statement-count" class="font-medium"></span></div>
                            <div>压缩率: <span id="compression-ratio" class="font-medium"></span></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- SQL 验证结果 -->
            <div id="sql-validation" class="mt-6 hidden">
                <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                    <i data-feather="shield" class="w-5 h-5 mr-2"></i>
                    验证结果
                </h3>
                
                <div class="grid md:grid-cols-2 gap-4">
                    <!-- 语法问题 -->
                    <div id="sql-issues" class="bg-red-50 border border-red-200 rounded-lg p-4">
                        <h4 class="font-semibold text-red-800 mb-2 flex items-center">
                            <i data-feather="alert-circle" class="w-4 h-4 mr-2"></i>
                            语法问题
                        </h4>
                        <div id="issues-list" class="text-sm text-red-700"></div>
                    </div>
                    
                    <!-- 建议优化 -->
                    <div id="sql-suggestions" class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                        <h4 class="font-semibold text-yellow-800 mb-2 flex items-center">
                            <i data-feather="lightbulb" class="w-4 h-4 mr-2"></i>
                            优化建议
                        </h4>
                        <div id="suggestions-list" class="text-sm text-yellow-700"></div>
                    </div>
                </div>
            </div>

            <!-- 表名提取结果 -->
            <div id="table-extraction" class="mt-6 hidden">
                <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                    <i data-feather="database" class="w-5 h-5 mr-2"></i>
                    提取的表名
                </h3>
                <div id="tables-list" class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                    <div class="flex flex-wrap gap-2" id="table-names"></div>
                </div>
            </div>

            <!-- 使用说明 -->
            <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-4 mt-6">
                <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                    <i data-feather="help-circle" class="w-5 h-5 mr-2"></i>
                    使用说明
                </h3>
                <div class="grid md:grid-cols-2 gap-4 text-sm text-blue-700">
                    <div>
                        <h4 class="font-semibold mb-2">格式化功能</h4>
                        <ul class="space-y-1">
                            <li>• 美化SQL语句结构和缩进</li>
                            <li>• 关键字大小写统一</li>
                            <li>• 自定义格式化选项</li>
                            <li>• 支持多语句格式化</li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="font-semibold mb-2">其他功能</h4>
                        <ul class="space-y-1">
                            <li>• SQL压缩：移除多余空格</li>
                            <li>• 语法验证：检查SQL语法</li>
                            <li>• 表名提取：自动识别表名</li>
                            <li>• 快捷键：Ctrl+Enter快速格式化</li>
                        </ul>
                    </div>
                </div>
            </div>
        `;
    }

    static init() {
        const sqlInput = document.getElementById('sql-input');
        const sqlOutput = document.getElementById('sql-output');
        const formatBtn = document.getElementById('format-sql');
        const minifyBtn = document.getElementById('minify-sql');
        const validateBtn = document.getElementById('validate-sql');
        const extractBtn = document.getElementById('extract-tables');
        const copyBtn = document.getElementById('copy-sql-result');
        const clearBtn = document.getElementById('clear-sql');
        const pasteBtn = document.getElementById('paste-sql');
        
        // 配置控件
        const indentSizeSelect = document.getElementById('indent-size');
        const keywordCaseSelect = document.getElementById('keyword-case');
        const commaStyleSelect = document.getElementById('comma-style');
        const linesBetweenSelect = document.getElementById('lines-between');
        
        // 状态显示
        const statusSpan = document.getElementById('sql-status');
        const sqlStats = document.getElementById('sql-stats');
        const sqlValidation = document.getElementById('sql-validation');
        const tableExtraction = document.getElementById('table-extraction');

        let currentResult = '';

        // 更新状态显示
        const updateStatus = (status) => {
            statusSpan.textContent = status;
        };

        // 更新统计信息
        const updateStats = () => {
            const lines = sqlInput.value.split('\n').length;
            document.getElementById('sql-input-count').textContent = sqlInput.value.length;
            document.getElementById('sql-input-lines').textContent = lines;
        };

        // 显示结果统计
        const showResultStats = (originalLength, formattedLength, statementCount) => {
            document.getElementById('original-length').textContent = originalLength;
            document.getElementById('formatted-length').textContent = formattedLength;
            document.getElementById('statement-count').textContent = statementCount;
            
            const ratio = originalLength > 0 ? 
                ((1 - formattedLength / originalLength) * 100).toFixed(1) : '0';
            document.getElementById('compression-ratio').textContent = ratio + '%';
            
            sqlStats.classList.remove('hidden');
        };

        // 格式化SQL
        const formatSQL = () => {
            const input = sqlInput.value.trim();
            if (!input) {
                DevToolsUtils.showToast('请输入SQL语句', 'error');
                return;
            }

            DevToolsUtils.addLoading(formatBtn);
            updateStatus('格式化中...');

            setTimeout(() => {
                try {
                    const options = {
                        indentSize: parseInt(indentSizeSelect.value),
                        keywordCase: keywordCaseSelect.value,
                        commaStyle: commaStyleSelect.value,
                        linesBetween: parseInt(linesBetweenSelect.value)
                    };

                    const result = SQLFormatter.format(input, options);
                    
                    if (result.success) {
                        currentResult = result.data;
                        sqlOutput.textContent = result.data;
                        DevToolsUtils.addSuccessBorder(sqlInput);
                        showResultStats(input.length, result.data.length, result.statementCount || 1);
                        copyBtn.disabled = false;
                        updateStatus('格式化完成');
                        DevToolsUtils.showToast('SQL 格式化成功！');
                    } else {
                        sqlOutput.textContent = `格式化失败: ${result.error}`;
                        DevToolsUtils.addErrorBorder(sqlInput);
                        updateStatus('格式化失败');
                        DevToolsUtils.showToast(result.error, 'error');
                    }
                } catch (error) {
                    sqlOutput.textContent = `格式化错误: ${error.message}`;
                    DevToolsUtils.addErrorBorder(sqlInput);
                    updateStatus('格式化失败');
                    DevToolsUtils.showToast('SQL 格式化失败', 'error');
                }
                
                DevToolsUtils.removeLoading(formatBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        };

        // 压缩SQL
        const minifySQL = () => {
            const input = sqlInput.value.trim();
            if (!input) {
                DevToolsUtils.showToast('请输入SQL语句', 'error');
                return;
            }

            DevToolsUtils.addLoading(minifyBtn);
            updateStatus('压缩中...');

            setTimeout(() => {
                try {
                    const result = SQLFormatter.minify(input);
                    
                    if (result.success) {
                        currentResult = result.data;
                        sqlOutput.textContent = result.data;
                        DevToolsUtils.addSuccessBorder(sqlInput);
                        showResultStats(input.length, result.data.length, result.statementCount || 1);
                        copyBtn.disabled = false;
                        updateStatus('压缩完成');
                        
                        const savedBytes = input.length - result.data.length;
                        const savedPercent = Math.round((savedBytes / input.length) * 100);
                        DevToolsUtils.showToast(`压缩完成，节省了 ${savedBytes} 字符 (${savedPercent}%)`);
                    } else {
                        sqlOutput.textContent = `压缩失败: ${result.error}`;
                        DevToolsUtils.addErrorBorder(sqlInput);
                        updateStatus('压缩失败');
                        DevToolsUtils.showToast(result.error, 'error');
                    }
                } catch (error) {
                    sqlOutput.textContent = `压缩错误: ${error.message}`;
                    DevToolsUtils.addErrorBorder(sqlInput);
                    updateStatus('压缩失败');
                    DevToolsUtils.showToast('SQL 压缩失败', 'error');
                }
                
                DevToolsUtils.removeLoading(minifyBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        };

        // 验证SQL
        const validateSQL = () => {
            const input = sqlInput.value.trim();
            if (!input) {
                DevToolsUtils.showToast('请输入SQL语句', 'error');
                return;
            }

            DevToolsUtils.addLoading(validateBtn);
            updateStatus('验证中...');

            setTimeout(() => {
                try {
                    const result = SQLFormatter.validate(input);
                    
                    if (result.success) {
                        const data = result.data;
                        
                        // 显示问题
                        const issuesList = document.getElementById('issues-list');
                        if (data.issues && data.issues.length > 0) {
                            issuesList.innerHTML = data.issues.map(issue => 
                                `<div class="mb-1">• ${issue}</div>`
                            ).join('');
                        } else {
                            issuesList.innerHTML = '<div class="text-green-600">未发现语法问题</div>';
                        }
                        
                        // 显示建议
                        const suggestionsList = document.getElementById('suggestions-list');
                        if (data.suggestions && data.suggestions.length > 0) {
                            suggestionsList.innerHTML = data.suggestions.map(suggestion => 
                                `<div class="mb-1">• ${suggestion}</div>`
                            ).join('');
                        } else {
                            suggestionsList.innerHTML = '<div class="text-gray-500">暂无优化建议</div>';
                        }
                        
                        sqlValidation.classList.remove('hidden');
                        DevToolsUtils.addSuccessBorder(sqlInput);
                        updateStatus('验证完成');
                        DevToolsUtils.showToast('SQL 验证完成！');
                    } else {
                        DevToolsUtils.addErrorBorder(sqlInput);
                        updateStatus('验证失败');
                        DevToolsUtils.showToast(result.error, 'error');
                    }
                } catch (error) {
                    DevToolsUtils.addErrorBorder(sqlInput);
                    updateStatus('验证失败');
                    DevToolsUtils.showToast('SQL 验证失败', 'error');
                }
                
                DevToolsUtils.removeLoading(validateBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        };

        // 提取表名
        const extractTables = () => {
            const input = sqlInput.value.trim();
            if (!input) {
                DevToolsUtils.showToast('请输入SQL语句', 'error');
                return;
            }

            DevToolsUtils.addLoading(extractBtn);
            updateStatus('提取中...');

            setTimeout(() => {
                try {
                    const result = SQLFormatter.extractTables(input);
                    
                    if (result.success && result.data.length > 0) {
                        const tableNames = document.getElementById('table-names');
                        tableNames.innerHTML = result.data.map(table => 
                            `<span class="inline-block bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium">${table}</span>`
                        ).join('');
                        
                        tableExtraction.classList.remove('hidden');
                        DevToolsUtils.addSuccessBorder(sqlInput);
                        updateStatus('提取完成');
                        DevToolsUtils.showToast(`成功提取 ${result.data.length} 个表名！`);
                    } else {
                        DevToolsUtils.showToast('未找到表名', 'warning');
                        updateStatus('未找到表名');
                    }
                } catch (error) {
                    updateStatus('提取失败');
                    DevToolsUtils.showToast('表名提取失败', 'error');
                }
                
                DevToolsUtils.removeLoading(extractBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        };

        // 清空内容
        const clearAll = () => {
            sqlInput.value = '';
            sqlOutput.textContent = '';
            currentResult = '';
            DevToolsUtils.removeStatusBorder(sqlInput);
            sqlStats.classList.add('hidden');
            sqlValidation.classList.add('hidden');
            tableExtraction.classList.add('hidden');
            copyBtn.disabled = true;
            updateStats();
            updateStatus('就绪');
        };

        // 复制结果
        const copyResult = async () => {
            if (currentResult) {
                await DevToolsUtils.copyToClipboard(currentResult);
                DevToolsUtils.showToast('已复制到剪贴板！');
            } else {
                DevToolsUtils.showToast('没有可复制的内容', 'error');
            }
        };

        // 粘贴内容
        const pasteContent = async () => {
            try {
                const text = await navigator.clipboard.readText();
                sqlInput.value = text;
                updateStats();
                DevToolsUtils.showToast('粘贴成功！');
            } catch (err) {
                DevToolsUtils.showToast('粘贴失败，请手动粘贴', 'error');
            }
        };

        // 事件监听器
        sqlInput.addEventListener('input', DevToolsUtils.debounce(() => {
            updateStats();
            updateStatus('输入中...');
            
            if (sqlInput.value.trim()) {
                updateStatus('准备处理');
                DevToolsUtils.removeStatusBorder(sqlInput);
            } else {
                updateStatus('就绪');
            }
        }, 300));

        formatBtn.addEventListener('click', formatSQL);
        minifyBtn.addEventListener('click', minifySQL);
        validateBtn.addEventListener('click', validateSQL);
        extractBtn.addEventListener('click', extractTables);
        copyBtn.addEventListener('click', copyResult);
        clearBtn.addEventListener('click', clearAll);
        pasteBtn.addEventListener('click', pasteContent);

        // 快捷键支持
        sqlInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && e.ctrlKey) {
                formatSQL();
            }
        });

        // 初始化
        updateStats();
        updateStatus('就绪');
        
        // 初始化 Feather 图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};